package dao;

import domain.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TestDao extends BaseDao {

    public void add(User user) {
        getHibernateTemplate().save(user);
    }


    public void updateUser(User user) {
        getHibernateTemplate().update(user);
    }

    public User getUser(Long userId) {
        return getHibernateTemplate().get(User.class, userId);
    }

    public List<User> findByName(String username) {
        return (List<User>) getHibernateTemplate().find("From t_user LIKE ?", "%" + username + "%");
    }

    public long getUserNum() {
        Object object = getHibernateTemplate().iterate("SELECT COUNT(id) FROM t_user").next();
        return Long.class.cast(object);
    }


    public long getUserNum2() {
        return getHibernateTemplate().execute(new HibernateCallback<Long>() {
            public Long doInHibernate(Session session) throws HibernateException {
                Object object = session.createQuery("SELECT COUNT(id) FROM t_user").list().iterator().next();
                return (Long) object;
            }
        });
    }
}
